package ${package.Stereotype}.security.filter;

import ${package.Stereotype}.security.bean.LoginUser;
import ${package.Stereotype}.security.impl.CacheServiceImpl;
import ${package.Stereotype}.util.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    private UserDetailsService userDetailsService;

    CacheServiceImpl cache;

    /**
     * 会从 Spring Security 配置文件那里传过来
     */
    public JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserDetailsService userDetailsService, CacheServiceImpl cache) {
        super(authenticationManager);
        this.userDetailsService = userDetailsService;
        this.cache = cache;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 判断是否有 token，并且进行认证
        Authentication token = getAuthentication(request);
        //SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(null,null,null));
        if (token != null) {
            SecurityContextHolder.getContext().setAuthentication(token);
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasLength(token)) return null;
        String username = JwtUtil.getUsername(token);
        if(!StringUtils.hasLength(username)) return null;
        LoginUser user = cache.getLoginUser(username);
        if (user == null) return null;
        if (!JwtUtil.verify(token, username, user.getPwd())) return null;
        cache.setLoginUser(user);
        <#assign GrantedAuthority = 'GrantedAuthority' />
        List<${GrantedAuthority}> grantedAuthorities = new ArrayList<>();
        if (user != null)
            user.getRoleIds().stream().forEach(roleId -> grantedAuthorities.add(new SimpleGrantedAuthority(roleId)));
        return new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPwd(), grantedAuthorities);
    }
}

